import { toChartData } from "@/comm/format";
import { Bus, CHART_KLINE__ITEM, CHART_KLINE__LIST } from "./Bus";
import { IBroadcast } from "./IBroadcast";

export class KlineBroadcast extends IBroadcast {
    channelParam = {
        event: "subscribe",
        symbol: "",
        topic: "kline",
        interval: "S1"
    };
    symbol = "";
    interval = "";
    channelStr = "";

    changeParam(symbol: string, interval: string) {
        console.warn("symbol", symbol, "interval", interval)
        this.symbol = symbol;
        // if (this.interval == "") {
        this.interval = interval;
        // }

        this.channelParam = {
            event: "subscribe",
            symbol: this.symbol,
            topic: "kline",
            interval: this.interval
        };
        this.subscribe();
    }

    changeSymbol(symbol: string) {
        this.symbol = symbol;
        this.channelParam.symbol = symbol;
        this.subscribe();
    }

    changeInterval(interval: string) {
        this.interval = interval;
        this.channelParam.interval = interval;
        this.subscribe();
    }

    subscribe(): void {
        this.unSubscribe();
        if (!this.channelParam) {
            console.log("订阅参数未初始化");
            return;
        }

        this.channelStr = JSON.stringify(this.channelParam);
        console.log("###订阅", this.channelStr);
        if (!this.channelParam.symbol){
            console.log("没有coin syboml");
            return
        }
        this.send(this.channelStr);
    }

    unSubscribe(): void {
        // console.warn("取消订阅 kline 开始")
        if (!this.channelStr) return;

        const obj = JSON.parse(this.channelStr);
        obj.event = "unsubscribe";
        console.log("###取消订阅", JSON.stringify(obj));
        this.send(JSON.stringify(obj));
    }

    handle(jsondata: any): void {
        //console.log(jsondata);
        if (jsondata.full) {
            const ary: any[] = [];
            jsondata.data.forEach((element: any, id: number) => {
                if (element) {
                    ary.push(toChartData(element));
                }
            });
            Bus.emit(CHART_KLINE__LIST, ary);
        } else {
            if (jsondata.data) {
                Bus.emit(CHART_KLINE__ITEM, toChartData(jsondata.data));
            }
        }
    }
}

// function toChartData(data: any) {
//     if (!data.startTime) {
//         console.error("錯誤的時間");
//     }
//     return {
//         close: data.close,
//         // high: data.height,
//         high: data.high,
//         low: data.low,
//         open: data.open,
//         timestamp: data.startTime,
//         volume: data.volume,
//         fundingRate: data.fundingRate || 0
//     };
// }
